﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PluginInterface;
using System.IO;
using System.Reflection;

namespace MainProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            string[] plugins = Directory.GetFiles("Plugins", "*dll");
            string pi = "";
            string typeName = "";
            foreach (string item in plugins)
            {
                Assembly ab = Assembly.Load(File.ReadAllBytes(item)); //加载内存中的Dll
                //Assembly ab = Assembly.LoadFile(item);  //直接加载 需要绝对路径
                bool flag = ab.GetTypes().Any(t =>
                {

                    object[] objAttrs = t.GetCustomAttributes(typeof(PluginAttribute), false);
                    if (t.GetInterface("IPlugin") != null && objAttrs.Length != 0)
                    {
                        PluginAttribute attr = objAttrs[0] as PluginAttribute;
                        string pluginName = attr.Name;
                        string pluginDescription = attr.Description;
                        typeName = t.FullName;
                        return true;
                    }
                    return false;
                });

                if (!flag) continue;
                pi = item;
            }

            Assembly assemble = Assembly.Load(File.ReadAllBytes(pi));
            IPlugin ip = (IPlugin)assemble.CreateInstance(typeName);
            ip.Show();
        }
    }
}
